#include "ConfigMgr.h"
#include <sstream>
#include <algorithm>
#include <cctype>

// 辅助函数：去除字符串首尾空白
static std::string Trim(const std::string& s) {
    // 处理空字符串情况
    if (s.empty()) {
        return "";
    }

    auto start = s.begin();
    while (start != s.end() && std::isspace(*start)) {
        start++;
    }

    // 如果整个字符串都是空白字符
    if (start == s.end()) {
        return "";
    }

    auto end = s.end();
    do {
        end--;
    } while (std::distance(start, end) > 0 && std::isspace(*end));

    return std::string(start, end + 1);
}

ConfigMgr::ConfigMgr() {
    // 获取当前工作目录
    fs::path current_path = fs::current_path();
    // 构建config.ini文件的完整路径
    fs::path config_path = current_path / "config.ini";
    std::cout << "Config path: " << config_path << std::endl;

    // 解析INI文件
    if (!ParseIniFile(config_path.string())) {
        std::cerr << "Failed to parse config file: " << config_path << std::endl;
    }

    // 输出所有的section和key-value对
    for (const auto& section_entry : _config_map) {
        const std::string& section_name = section_entry.first;
        const SectionInfo& section_config = section_entry.second;
        std::cout << "[" << section_name << "]" << std::endl;
        for (const auto& key_value_pair : section_config._section_datas) {
            std::cout << key_value_pair.first << "=" << key_value_pair.second << std::endl;
        }
    }

    InitPath();
}

// 实现INI文件解析
bool ConfigMgr::ParseIniFile(const std::string& filename) {
    std::ifstream file(filename);
    if (!file.is_open()) {
        return false;
    }

    std::string line;
    std::string current_section;
    SectionInfo current_section_info;

    while (std::getline(file, line)) {
        // 去除首尾空白
        line = Trim(line);

        // 跳过空行和注释
        if (line.empty() || line[0] == ';' || line[0] == '#') {
            continue;
        }

        // 处理section
        if (line[0] == '[' && line.back() == ']') {
            // 如果已经有当前section，保存它
            if (!current_section.empty()) {
                _config_map[current_section] = current_section_info;
                current_section_info._section_datas.clear();
            }

            // 提取section名称
            current_section = line.substr(1, line.size() - 2);
            current_section = Trim(current_section);
        }
        // 处理key=value对
        else {
            size_t eq_pos = line.find('=');
            if (eq_pos != std::string::npos) {
                std::string key = Trim(line.substr(0, eq_pos));
                std::string value = Trim(line.substr(eq_pos + 1));

                current_section_info._section_datas[key] = value;
            }
        }
    }

    // 保存最后一个section
    if (!current_section.empty()) {
        _config_map[current_section] = current_section_info;
    }

    return true;
}

std::string ConfigMgr::GetValue(const std::string& section, const std::string& key) {
    auto it = _config_map.find(section);
    if (it == _config_map.end()) {
        return "";
    }

    return it->second.GetValue(key);
}

fs::path ConfigMgr::GetFileOutPath() {
    return _static_path;
}

void ConfigMgr::InitPath() {
    // 获取当前工作目录
    fs::path current_path = fs::current_path();
    std::string bindir = _config_map["Output"].GetValue("Path");
    std::string staticdir = _config_map["Static"].GetValue("Path");
    std::string logdir = _config_map["Log"].GetValue("Path");

    _log_path = current_path / logdir;
    _static_path = current_path / bindir / staticdir;
    _bin_path = current_path / bindir;

    // 检查路径是否存在
    if (!fs::exists(_static_path)) {
        // 如果路径不存在，创建它
        if (fs::create_directories(_static_path)) {
            std::cout << "路径已成功创建: " << _static_path.string() << std::endl;
        }
        else {
            std::cerr << "创建路径失败: " << _static_path.string() << std::endl;
        }
    }
    else {
        std::cout << "路径已存在: " << _static_path.string() << std::endl;
    }
}
